<template>
  <div class="vm">
    <h2 class="h-title">绘制点、线、面</h2>
    <div class="tools-x">
      <select id="type" v-model="tool">
        <option v-for="item in tools" :key="item.value" :value="item.value">
          {{ item.label }}
        </option>
      </select>
    </div>
    <button @click="getData">读取</button>
    <button @click="clearLayer">清除</button>
    <button @click="hideLayer">隐藏图层</button>

    <div ref="map" class="map-x"></div>
  </div>
</template>

<script>
import "ol/ol.css";
import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import Draw from "ol/interaction/Draw";
import GeoJSON from "ol/format/GeoJSON";
import { Style, Text, Stroke, Fill, Circle } from "ol/style";
import GEOJSON_CONST from "../../assets/data/guangZhou.json";
export default {
  data() {
    return {
      tool: "Polygon", // 当前选中的工具
      tools: [
        // 工具集
        {
          value: "Point",
          label: "点",
        },
        {
          value: "LineString",
          label: "线",
        },
        {
          value: "Polygon",
          label: "多边形",
        },
        {
          value: "Circle",
          label: "圆",
        },
        {
          value: "None",
          label: "无",
        },
      ],
      className: "temporary",
      map: null, // 地图
      draw: null,
      source: new SourceVector({
        wrapX: false, // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
      }),
    };
  },
  watch: {
    tool(newVal) {
      this.addInteraction();
    },
  },
  methods: {
    getData() {
      // 如果localStorage无geo数据，初始化为数组[]
      if (!localStorage.getItem("geo")) {
        localStorage.setItem("geo", "[]");
      } else {
        //1.读取localStorage数据
        const result = JSON.parse(localStorage.getItem("geo"));
        //2.将 geoJSON 解析成 feature 并添加到 vectorLayer 数据源中
        result.forEach((item, index) => {
          const features = new GeoJSON().readFeatures(item.geom);
          //遍历feature添加style
          features.forEach((feature) => {
            const style = new Style({
              text: new Text({
                text: item.name,
                font: "normal 18px 黑体",
                textAlign: "center",
                fill: new Fill({
                  color: "rgba(255, 255, 255, 1)",
                }),
              }),
              stroke: new Stroke({
                color: "rgba(25, 137, 250, 1)",
                width: 3,
              }),
              fill: new Fill({
                color: "rgba(25, 137, 250, 0.1)",
              }),
              image: new Circle({
                //点样式
                radius: 5,
                fill: new Fill({
                  color: "rgba(25, 137, 250, 1)",
                }),
              }),
            });
            feature.setStyle(style);
          });
          // 3.将 feature 添加到 vectorLayer 数据源中
          var vectorSource = new SourceVector({
            features: features,
          });
          //4.使用数据源和显示方法构建图层
          var vectorLayer = new LayerVector({
            source: vectorSource,
          });
          this.map.addLayer(vectorLayer);
        });
      }
    },
    initMap() {
      let raster = new Tile({
        source: new OSM(),
      }); //背景图层

      //绘制点，线图层
      this.map = new Map({
        target: this.$refs.map,
        layers: [raster],
        view: new View({
          projection: "EPSG:4326",
          center: [113.1206, 23.034996],
          zoom: 10,
        }),
      });
    },
    getGuangZhou() {
      const result = new GeoJSON().readFeatures(GEOJSON_CONST);
      result.forEach((item) => {
        const style = new Style({
          text: new Text({
            text: item.values_.name,
            font: "normal 18px 黑体",
            textAlign: "center",
            fill: new Fill({
              color: "black",
            }),
          }),
          stroke: new Stroke({
            color: "green",
            width: 5,
          }),
          fill: new Fill({
            color: "rgba(255, 255, 0, 0.5)",
          }),
        });
        item.setStyle(style);
      });
      let source = new SourceVector({
        features: result,
      });

      this.geoLayer = new LayerVector({
        source: source,
        // 设置样式，边框和填充
      });
      // 添加GeoJSON到map上
      this.map.addLayer(this.geoLayer);
      // 地图视图缩小一点
      const view = this.map.getView();
      view.setZoom(9);
    },
    addInteraction() {
      let layer = new LayerVector({
        source: this.source,
        className: this.className,
      });
      this.map.addLayer(layer);
      this.draw = new Draw({
        source: this.source,
        type: this.tool,
      });
      this.map.addInteraction(this.draw);

      this.draw.on("drawend", (evt) => {
        this.map.removeInteraction(this.draw);
        let featureGeoJson = JSON.parse(
          new GeoJSON().writeFeature(evt.feature)
        );
        this.setData(featureGeoJson);
      });
    },
    setData(params) {
      const featureGeoJsonIN = {
        name: "测试事件111",
        geom: params,
      };
      const result = JSON.parse(JSON.stringify(featureGeoJsonIN));
      //读取localStorage数据再push，在setItem
      const geoRes = JSON.parse(localStorage.getItem("geo"))
      geoRes.push(result)
      localStorage.setItem("geo", JSON.stringify(geoRes))
    },
    // clearLayer() {
    //   localStorage.setItem("geo", "[]")
    // }
    hideLayer() {

    }
  },
  mounted() {
    this.initMap()
    this.getGuangZhou()
    this.getData()
  },
};
</script>

<style>
</style>